package com.wlz.authorization.config;

import com.wlz.authorization.handler.MyAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *  Authorization 授权
 *  基于权限的访问控制
 */
//@Configuration
//@EnableWebSecurity 基于springboot 可以不用
public class WebSecurityAntConfig2 extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin();  //表单登录

        //授权
        http.authorizeRequests()
//                .antMatchers("/admin/demo").permitAll() // 不用认证
//                .antMatchers( "/admin/demo").hasAuthority("admin") // 在配置类中通过 hasAuthority(“admin”)设置具有 admin 权限时才能访问。
//                .antMatchers( "/admin/demo").hasAuthority("admin1") // 在配置类中通过 hasAuthority(“admin”)设置具有 admin1 权限时才能访问。
                .antMatchers("/admin/demo").hasAnyAuthority("admin","system") //  如果用户具备给定权限中某一个，就允许访问。
                .anyRequest().authenticated();  //  必须认证

        http.exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler()); // 支持自定义权限受限处理，需要实现 AccessDeniedHandler接口
        http.csrf().disable();//csrf关掉

    }

    @Bean
    public PasswordEncoder passwordEncoder(){
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }


}
